package com.atguigu.tingshu.order.reciever;

import com.atguigu.tingshu.common.constant.KafkaConstant;
import com.atguigu.tingshu.order.service.OrderInfoService;
import jakarta.annotation.PostConstruct;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.redisson.api.RBlockingQueue;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

/**
 * @author: atguigu
 * @create: 2024-04-24 10:50
 */
@Slf4j
@Component
public class OrderCancelHandler {


    @Autowired
    private RedissonClient redissonClient;

    @Autowired
    private OrderInfoService orderInfoService;


    @PostConstruct
    public void delayCloseOrder() {
        //1.基于Redisson客户端对象创建阻塞队列
        RBlockingQueue<String> blockingQueue = redissonClient.getBlockingQueue(KafkaConstant.QUEUE_ORDER_CANCEL);
        //2.JUC线程池工具类中提供创建单一线程线程池方法
        ExecutorService executorService = Executors.newSingleThreadExecutor();
        executorService.submit(() -> {
            while (true) {
                String data = null;
                try {
                    data = blockingQueue.poll(5, TimeUnit.SECONDS);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
                if (StringUtils.isNotBlank(data)) {
                    log.info("监听延迟关单消息订单ID:{}", data);
                    orderInfoService.cancelOrder(Long.valueOf(data));
                }
            }
        });
    }
}
